let a1_edit;
let a2_edit;
let a3_edit;
let a4_edit;
$(function () {
    //图片
    a1_edit = buildFabricCanvas(document.getElementById('a1_edit'), "", "canvas1", 300, 300)
    //text
    a2_edit = buildFabricCanvas(document.getElementById('a2_edit'), "", "canvas2", 300, 300)
    addTextObjectToCanvas(a2_edit, "");
    bindThumbCanvasReloadEvent(a2_edit);
    //手写 黑色
    a3_edit = buildFabricCanvas(document.getElementById('a3_edit'), "", "canvas3", 300, 300)
    a3_edit.isDrawingMode = true;
    a3_edit.freeDrawingBrush.color = "black";
    a3_edit.freeDrawingBrush.width = 2;
    //手写 红色
    a4_edit = buildFabricCanvas(document.getElementById('a4_edit'), "", "canvas4", 300, 300)
    a4_edit.isDrawingMode = true;
    a4_edit.freeDrawingBrush.color = "red";
    a4_edit.freeDrawingBrush.width = 2;
});

function mergeAll(){
    let drawDiv = $('#a_show')[0]
    let svg1 = a1_edit.toJSON();
    buildFabricCanvas(drawDiv,svg1,'a1_edit_svg', 300, 300, true,false);
    let svg2 = a2_edit.toJSON();
    buildFabricCanvas(drawDiv,svg2,'a2_edit_svg', 300, 300, true,false);
    let svg3 = a3_edit.toJSON();
    buildFabricCanvas(drawDiv,svg3,'a3_edit_svg', 300, 300, true,false);
    let svg4 = a4_edit.toJSON();
    buildFabricCanvas(drawDiv,svg4,'a4_edit_svg', 300, 300, true,false);
}

function upImage() {
    addImageToCanvas(a1_edit);
}

function buildFabricCanvas(parentDivObject, svgBase64String, id, width, height, deleteFabricFlag, editableFlag) {
    //create canvas object instance
    let canvasObj = document.createElement("canvas");
    canvasObj.width = width;
    canvasObj.height = height;
    canvasObj.id = id;
    canvasObj.style.position = "absolute";
    canvasObj.style.zIndex = 0;
    parentDivObject.appendChild(canvasObj);
    if (!deleteFabricFlag) {
        parentDivObject.setAttribute("active_canvas_id", id);
    }
    canvasObj = new fabric.Canvas(canvasObj.id);
    canvasObj.hoverCursor = 'defaultCursor';

    //編集不可の場合、CanvasのdefaultCursorを「pointer」に設定する
    if (!editableFlag) {
        canvasObj.defaultCursor = "pointer";
    }

    fabric.isDrawingMode = false;
    //create empty canvas
    if (!svgBase64String) {
        return canvasObj;
    }

    // if (svgBase64String.indexOf("<!DOCTYPE svg PUBLIC") > 0 || svgBase64String.indexOf("<svg") > 0) {
    //     loadCanvasFromSvgString(canvasObj, svgBase64String, width, height);
    // } else {
    //     loadCanvasFromJsonString(canvasObj, svgBase64String, width, height);
    // }
    loadCanvasFromJsonString(canvasObj, svgBase64String, width, height);

    //delete lower-canvase canvas object
    if (deleteFabricFlag) {
        let parentDiv = document.getElementById(id).parentElement;
        let parentParentNode = parentDiv.parentElement;
        let upperCanvas = parentDiv.getElementsByClassName("upper-canvas").item(0);
        let lowerCanvas = parentDiv.getElementsByClassName("lower-canvas").item(0);
        parentDiv.removeChild(upperCanvas);
        parentDiv.removeChild(lowerCanvas);
        parentParentNode.removeChild(parentDiv);
        parentParentNode.appendChild(lowerCanvas);
    }
    return canvasObj;
}

function addTextObjectToCanvas(canvasObj, textStr) {
    let textObject = new fabric.Textbox(textStr, {
        id: "TEXT_AREA",
        left: 0,
        top: 0,
        fontSize: 21.3,
        lineHeight: 1.5,
        fontFamily: "bold NotoSansJP, meiryo, sans-serif",
        height: canvasObj.height,
        width: canvasObj.width,
        fixedHeight: canvasObj.height,
        // hasControls: true,
        borderColor: 'orange',
        // editingBorderColor: 'blue',
        // fill: "#000000",
        // selectable: false,
        lockMovementX: true,
        lockMovementY: true,
        hasControls: false,
        // editable: true,
        splitByGrapheme: true,
        hasBorders: false
    });

    canvasObj.add(textObject);
    canvasObj.setActiveObject(textObject);
    textObject.enterEditing();
    textObject.hiddenTextarea.focus();
}

function textBoxIsEdit(canDraw, isEdit) {
    if (canDraw.size() > 0) {
        canDraw.getObjects().forEach(function (item) {
            if (item.type === "textbox" && !item.readOnly) {
                if (isEdit) {
                    canDraw.setActiveObject(item);
                    // item.height = PARTS_GLOBAL_PARAMS.PARTS_EDIT_AREA_HEIGHT;
                    item.enterEditing();
                    item.hiddenTextarea.focus();
                }
                // else {
                //   // item.exitEditing();
                // }
                return;
            }
            else if (item.type === "textbox" && item.readOnly === true) {
                item.exitEditing();
                return;
            }
        })
    }
}

function addImageToCanvas(canvasObject, thumbCanvasObject, callableFunction) {
    let width = canvasObject.width;
    let height = canvasObject.height;

    let selectFile = selectFileDialog();
    selectFile.done(function (files) {
        canvasObject.clear();
        // thumbCanvasObject.clear();
        let reader = new FileReader();
        reader.readAsDataURL(files[0]);
        let fileExt = files[0].name.toLowerCase();
        fileExt = fileExt.substring(fileExt.indexOf(".") + 1, fileExt.length);

        if (callableFunction) {
            callableFunction();
        }

        if (fileExt === "heic") {
            let blob = files[0];
            heic2any({
                blob: blob,
                toType: "image/jpeg",
                quality: 0.5
            })
                .then(function (resultBlob) {
                    let readerHeic = new FileReader();
                    readerHeic.readAsDataURL(resultBlob);
                    readerHeic.onload = function (event) {
                        loadImage(event.target.result, canvasObject, width, height);
                    };

                })
        } else {
            reader.onload = function (event) {
                loadImage(event.target.result, canvasObject, width, height);
            };
        }
    });
}

function selectFileDialog() {
    let promise = $.Deferred();
    let input = $("<input type='file' accept='image/png,image/jpeg' />");
    if (window.chrome) {
        input.change(function () {
            promise.resolve(this.files);
        });
        input.click();
    } else {
        input.click();

        let time = window.setInterval(function () {
            let files = input[0].files;
            if (files.length > 0) {
                promise.resolve(files);
                clearInterval(time);
            }
        }, 100);
    }
    //else if (isAppleOS()) {
    //  input.change(function (e) {
    //    promise.resolve(e.target.files);
    //  });
    //
    //  input.click();
    //} else
    return promise;
}


function loadImage(imageSrc, canvasObject, width, height) {
    let imgInfo = {
        quality: 0.5,
        width: 300,
        height: 300
    }
    imageCompression(imageSrc, imgInfo, function (base64Codes) {
        let img = new Image();
        img.setAttribute('crossOrigin', 'anonymous');
        img.src = base64Codes;
        img.onload = function () {
            let result = calculatePicture(img, width, height);

            let imgInstance = new fabric.Image(img, {
                left: result.startWidth,
                top: 0,

                width: result.originWidth,
                height: result.originHeight,
                // selectable: false
                lockMovementX: true,
                lockMovementY: true,
                hasControls: false,
                hasBorders: false
            });
            imgInstance.scale(result.scaleValue);

            canvasObject.add(imgInstance);
        };
    });
}

function imageCompression(path, obj, callback) {
    let img = new Image();
    img.src = path;
    img.onload = function () {
        let that = this;

        let w = that.width;
        let h = that.height;

        if (w < obj.width && h < obj.height) {
            callback(that.src);
            return;
        }

        let quality = 0.5; // 0.7

        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');

        let anw = document.createAttribute('width');
        anw.nodeValue = w;
        let anh = document.createAttribute('height');
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);

        if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
            quality = obj.quality;
        }

        let base64 = canvas.toDataURL('image/jpeg', quality)

        callback(base64);
    }
}

function calculatePicture(img, width, height) {
    let result = { startWidth: 0, originWidth: 0, originHeight: 0, scaleValue: 1 };
    result.originWidth = img.width;
    result.originHeight = img.height;
    result.scaleValue = 1;

    if (result.originWidth > width || result.originHeight > height) {
        if (height / result.originHeight > width / result.originWidth) {
            result.scaleValue = width / result.originWidth;
        } else {
            result.scaleValue = height / result.originHeight;
        }
    }
    result.startWidth = (width - img.width * result.scaleValue) / 2;
    return result;
}






function bindThumbCanvasReloadEvent(editCanvas) {
    editCanvas.on('mouse:down', function (e) {
        textBoxIsEdit(editCanvas, true);
    });
}

function loadCanvasFromJsonString(canvasObj, jsonString, width, height) {
    let scale = 1
    try {
        canvasObj.loadFromJSON(jsonString, canvasObj.requestRenderAll.bind(canvasObj), function (o, item) {
            item.lockMovementX = true;
            item.lockMovementY = true;

            item.hasControls = false;
            item.hasBorders = false;
            item.splitByGrapheme = true;

        });
    } catch (e) {
        console.log(e);
    }

    canvasObj.setZoom(scale);
}

function loadCanvasFromSvgString(canvasObj, svgString, width, height) {
    fabric.loadSVGFromString(svgString, function (objects, options) {
      $.each(objects, function (index, value) {
        if (value.id && value.id === 'erasure') {
          value.set({
            globalCompositeOperation: 'destination-out'
          });
        }
      });
      let svgGroups = fabric.util.groupSVGElements(objects, options);
  
      svgGroups.set({
        scaleY: height / PARTS_GLOBAL_PARAMS.PARTS_EDIT_AREA_HEIGHT,
        scaleX: width / PARTS_GLOBAL_PARAMS.PARTS_EDIT_AREA_WIDTH
      });
  
      svgGroups.lockMovementX = true;
      svgGroups.lockMovementY = true;
      svgGroups.hasControls = false;
      svgGroups.hasBorders = false;
  
      canvasObj.add(svgGroups).requestRenderAll();
    });
  }